<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '登录',
  },
}
</route>

<template>
  <view class="w-center">
    <view class="pt-24rpx">
      
      <!--  #ifdef MP-WEIXIN -->
      <!-- <view class="w-full h-160rpx"
        v-if="common.phoneLoginConfig.typeName === 'true'"
      ></view> -->
      <!--  #endif -->
      
      <view class="flex-center font-size-0 mb-24rpx">
        <wd-img 
          width="100px" 
          height="100px" 
          radius="100px" 
          :src="logo" 
          mode="aspectFill" 
        />
      </view>

      <!-- 标题 -->
      <view class="text-center font-size-56rpx">
        <wd-text text="欢迎登陆" lineHeight="66rpx"></wd-text>
        <wd-text text="丹身乐缘" color="#9C6DEF" lineHeight="66rpx"></wd-text>
      </view>

      <!--  #ifdef H5 -->
      <wd-form ref="form" :model="fromData" errorType="toast">
        <!-- 手机号 -->
        <view class="bg-white h-100rpx rd-100rpx mt-34rpx pl-40rpx pr-40rpx flex"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="flex-none w-64rpx h-full mr-2 flex-center">
            <i class="iconfont icon-phone font-size-56rpx"></i>
          </view>
          <view class="w-100rpx h-full flex-center mr-32rpx">
            +86<i class="iconfont icon-arrow-down ml-8rpx font-size-28rpx"></i>
          </view>
          <view class="h-full flex-center">
            <wd-input
              label="手机号"
              label-width="100px"
              prop="phone"
              clearable
              v-model="fromData.phone"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
          </view>
        </view>

        <!-- 验证码 -->
        <view class="bg-white h-100rpx rd-100rpx mt-48rpx pl-40rpx pr-40rpx flex-sb-center"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="h-full flex-center">
            <wd-input
              label="验证码"
              label-width="100px"
              prop="code"
              clearable
              v-model="fromData.code"
              placeholder="请输入验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
            />
          </view>
          <view class="w-160rpx h-full flex-center" @click="sendCode">
            <wd-text v-if="status === 'normal'" text="获取验证码" color="#986DF0" size="26rpx"></wd-text>
            <wd-text v-else-if="status === 'sending'" text="发送中..." color="#986DF0" size="26rpx"></wd-text>
            <wd-count-down v-if="status === 'finish'" :time="time" format="ss 秒" @finish="onFinish" />
          </view>
        </view>
      </wd-form>
      <!--  #endif -->

      <!--  #ifdef MP-WEIXIN -->
      <wd-form ref="form" :model="fromData" errorType="toast"
        v-if="common.phoneLoginConfig.typeName === 'false'"
      >
        <!-- 手机号 -->
        <view class="bg-white h-100rpx rd-100rpx mt-34rpx pl-40rpx pr-40rpx flex"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="flex-none w-64rpx h-full mr-2 flex-center">
            <i class="iconfont icon-phone font-size-56rpx"></i>
          </view>
          <view class="w-100rpx h-full flex-center mr-32rpx">
            +86<i class="iconfont icon-arrow-down ml-8rpx font-size-28rpx"></i>
          </view>
          <view class="h-full flex-center">
            <wd-input
              label="手机号"
              label-width="100px"
              prop="phone"
              clearable
              v-model="fromData.phone"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
          </view>
        </view>

        <!-- 验证码 -->
        <view class="bg-white h-100rpx rd-100rpx mt-48rpx pl-40rpx pr-40rpx flex-sb-center"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="h-full flex-center">
            <wd-input
              label="验证码"
              label-width="100px"
              prop="code"
              clearable
              v-model="fromData.code"
              placeholder="请输入验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
            />
          </view>
          <view class="w-160rpx h-full flex-center" @click="sendCode">
            <wd-text v-if="status === 'normal'" text="获取验证码" color="#986DF0" size="26rpx"></wd-text>
            <wd-text v-else-if="status === 'sending'" text="发送中..." color="#986DF0" size="26rpx"></wd-text>
            <wd-count-down v-if="status === 'finish'" :time="time" format="ss 秒" @finish="onFinish" />
          </view>
        </view>
      </wd-form>
      <!--  #endif -->
        
      <!-- 协议 -->
      <view class="mt-112rpx font-size-24rpx flex-a-center">
        <wd-checkbox v-model="checked">
          <wd-text text="我已阅读并同意" color="#323233"></wd-text>
        </wd-checkbox>
        <wd-text text="《隐私政策》" color="#165DFF" @click="toPath('/feature/richtext?code=2')"></wd-text>
        <wd-text text="和" color="#323233"></wd-text>
        <wd-text text="《注册协议》" color="#165DFF" @click="toPath('/feature/richtext?code=3')"></wd-text>
      </view>
      
      <!-- <view class="w-full h-100rpx mt-20rpx">
        <wd-button 
          custom-class="btn-com bg-color-main" 
          :disabled="false" 
          :loading="loginLoading"
          @click="submit"
        >登  录</wd-button>
      </view> -->

      <!-- 登录按钮 -->
      <!--  #ifdef H5 -->
      <view class="w-full h-100rpx mt-20rpx">
        <wd-button 
          custom-class="btn-com bg-color-main" 
          :disabled="false" 
          :loading="loginLoading"
          @click="submit"
        >登  录</wd-button>
      </view>
      <!--  #endif -->
        
      <!--  #ifdef MP-WEIXIN -->
      <view class="w-full h-100rpx mt-20rpx">
        <wd-button 
          custom-class="btn-com bg-color-main" 
          :disabled="false" 
          :loading="loginLoading"
          @click="wxSubmit"
        >登  录</wd-button>
      </view>
      <!-- <view class="w-full h-100rpx mt-20rpx">
        <wd-button 
          custom-class="btn-com bg-color-main" 
          :loading="loginLoading"
          @getphonenumber="getphonenumber"
          open-type="getPhoneNumber"
        >手机号快捷登录</wd-button>
      </view> -->
      <!--  #endif -->

      <view class="mt-48rpx text-center">
        <wd-text text="手机号验证后即可完成注册" color="#986DF0" size="28rpx"></wd-text>
      </view>

      <!-- 底部其它登录方式 -->
      <!--  #ifdef H5 -->
      <view class="position-b-center">
        <view class="text-center font-size-24rpx pb-46rpx">
          <wd-text text="其它登录方式" color="#969799"></wd-text>
        </view>
        <view class="flex-center mb-32rpx" @click="wxLogin">
          <i class="iconfont icon-wx font-size-64rpx color-#00C800"></i>
        </view>
        <view class="w-full h-30rpx"></view>
      </view>
      <!--  #endif -->

      <!--  #ifdef MP-WEIXIN -->
      <!-- <view class="position-b-center" v-if="common.phoneLoginConfig.typeName === 'false'">
        <view class="text-center font-size-24rpx pb-46rpx">
          <wd-text text="其它登录方式" color="#969799"></wd-text>
        </view>
        <view class="flex-center mb-32rpx relative">
          <wd-button 
            v-if="!loginLoading"
            custom-class="share-btn"
            @getphonenumber="getphonenumber"
            open-type="getPhoneNumber"
          >手机号快捷登录</wd-button>
          <i class="iconfont icon-wx font-size-64rpx color-#00C800"></i>
        </view>
        <view class="w-full h-30rpx"></view>
      </view> -->
      <!--  #endif -->
    </view>
  </view>
</template>

<script lang="ts" setup>
import { AliyunsmsSendSms, LoginPhone } from '@/service/db_index';
import { GetPhoneByWechatCode } from '@/service/db_user';
import { useThemeStore, useUserStore, useCommonStore } from '@/store';
import { useToast } from 'wot-design-uni';
import { logo } from "@/enum/index";

const toast = useToast();
// 主题颜色
const { themeConfig } = useThemeStore();
const userStore = useUserStore();
const common = useCommonStore();

const { windowHeight, safeAreaInsets } = uni.getSystemInfoSync();
// #ifdef H5  
// 获取屏幕边界到安全区域距离
const _body = document.querySelector('body');
_body.style.height = windowHeight + 'px';
// #endif

const checked = ref(false)
const fromData = reactive({
  instrId: userStore.instrId,
  source: userStore.source,
  phone: '',
  code: '',
  wechatCode: '',
})

const status = ref('normal');
const countDownTime = 60 * 1000;
const time = ref<number>(countDownTime);

/** 发送验证码 */
const sendCode = async () => {
  try {
    if (status.value !== 'normal') return;
    if (!fromData.phone) return toast.show('请填写手机号！');
    if (!checked.value) return toast.show('请先阅读协议！');
    
    status.value = 'sending';
    await AliyunsmsSendSms({
      phoneNum: fromData.phone.trim()
    })
    status.value = 'finish';
    toast.show('发送成功！');
    uni.hideLoading();
  } catch (error) {
    status.value = 'normal';
    console.log(error)
  }
}

/** 倒计时结束 */
const onFinish = () => {
  time.value = countDownTime;
  status.value = 'normal';
}

const pathType = ref('');
const loginLoading = ref(false);

// 登录
const handleLogin = async(code = '') => {
  try {
    loginLoading.value = true;
    const _data = {
      ...fromData,
      phone: fromData.phone.trim()
    }
    code && (_data.wechatCode = code);
    console.log('login data------->', _data)
    const res = await LoginPhone(_data);

    userStore.loginSubmit = true;
    userStore.setToken(res.data.token);
    userStore.getUserInfo({
      id: res.data.id,
      isLogin: true
    });
    toast.show('登录成功!');
    setTimeout(() => {
      loginLoading.value = false;
      if (pathType.value === 'logout') {
        return uni.reLaunch({ url: '/pages/tabbar/index' });
      }
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    console.log('handleLogin', error)
  } finally {
    loginLoading.value = false;
  }
}

/** 提交表单 */
const submit = async() => {
  try {
    if (!fromData.phone) return toast.show('请填写手机号！');
    if (!fromData.code) return toast.show('请填写验证码！');
    handleLogin();
  } catch (error) {
    loginLoading.value = false;
    console.log(error)
  }
}

// 微信登录
const wxSubmit = async() => {
  try {
    if (!fromData.phone) return toast.show('请填写手机号！');
    if (!fromData.code) return toast.show('请填写验证码！');
    
    uni.login({
      "provider": "weixin",
      "onlyAuthorize": true, // 微信登录仅请求授权认证
      success: function(event){
        const { code } = event;
        handleLogin(code);
      },
      fail: function (err) {
        // 登录授权失败
        // err.code是错误码
        console.log('登录授权失败err', err)
      }
    })
  } catch (error) {
    loginLoading.value = false;
    console.log(error)
  }
}

// 获取手机号
const getphonenumber = async(res) => {
  if (res.errMsg === 'getPhoneNumber:fail user deny') return;
  if (!checked.value) return toast.show('请先阅读协议！');
  try {
    loginLoading.value = true;
    const _res = await GetPhoneByWechatCode({ code: res.code });
    userStore.wxLogin(() => {
      userStore.loginSubmit = true;
      setTimeout(() => {
        loginLoading.value = false;
        if (pathType.value === 'logout') {
          return uni.reLaunch({ url: '/pages/tabbar/index' });
        }
        uni.navigateBack()
      }, 1000)
    }, _res.data.phoneNumber)
  } catch (error) {
    loginLoading.value = false;
    console.log('获取手机号失败err', error)
  }
}

// h5微信登录
const wxLogin = () => {
  toast.show('h5暂不支持微信登录');
}

const toPath = (path) => {
  uni.navigateTo({ url: path })
}

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '登录';
  })
})

onLoad((options) => {
  const { type } = options || {};
  pathType.value = type;
})
</script>
  
<style lang="scss" scoped>
:root,
page {
  height: 100%;
}

:deep(.wd-checkbox) {
  .wd-checkbox__shape {
    border-width: 1px;
  }
  .wd-checkbox__txt {
    font-size: 24rpx;
  }
  .wd-checkbox__label {
    margin-left: 6rpx;
  }
}

:deep(.wd-input__label) {
  display: none !important;
}

:deep(.wd-input) {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
</style>
